package com.ruoyi.user.controller;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.SpffUsers;
import com.ruoyi.user.dto.*;
import com.ruoyi.user.service.IEmailService;
import com.ruoyi.user.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Slf4j
@RestController
public class UserController {

    @Autowired
    private SysLoginService loginService;

    @Resource
    private IUserService userService;
    
    @Resource
    private IEmailService emailService;
    
    @Autowired
    private TokenService tokenService;
    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
//    @PostMapping("/login")
//    public AjaxResult login(@RequestBody LoginBody loginBody)
//    {
//        AjaxResult ajax = AjaxResult.success();
//
//        userService.login(loginForm, session);
//        // 生成令牌
//        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
//                loginBody.getUuid());
//        ajax.put(Constants.TOKEN, token);
//        return ajax;
//    }


    /**
     * 登录功能r
     * @param loginForm 登录参数，包含手机号、验证码；或者手机号、密码
     */
    @PostMapping("/userLogin")
    public AjaxResult login(@RequestBody LoginFormDTO loginForm, HttpSession session){
        // 实现登录功能
        return userService.login(loginForm, session);
    }

    /**
     * 登出功能
     * @return 无
     */
    @PostMapping("/logout")
    public Result logout(HttpServletRequest request){
        try {
            // 使用与管理端统一的Token机制登出
            LoginUser loginUser = tokenService.getLoginUser(request);
            if (loginUser != null) {
                tokenService.delLoginUser(loginUser.getToken());
            }
            return Result.ok("登出成功");
        } catch (Exception e) {
            log.error("登出失败", e);
            return Result.fail("登出失败");
        }
    }

//    @GetMapping("/me")
//    public Result me(HttpServletRequest request){
//        // 使用与管理端统一的Token机制获取用户信息
//        LoginUser loginUser = tokenService.getLoginUser(request);
//        if (loginUser == null) {
//            return Result.fail("用户未登录");
//        }
//
//        // 转换为UserDTO返回
//        UserDTO userDTO = new UserDTO();
//        userDTO.setId(loginUser.getUserId());
//        userDTO.setUsername(loginUser.getUsername());
//        return Result.ok(userDTO);
//    }

//    @GetMapping("/me")
//    public Result me(Long userId){
//        userService.getUserInfo()
//        return Result.ok(userDTO);
//    }

    /**
     * 关注用户
     * @param targetUserId 目标用户ID
     * @return 操作结果
     */
    @PostMapping("/user/follow")
    public Result followUser(@RequestParam("targetUserId") Long targetUserId, HttpServletRequest request) {
        try {
            LoginUser loginUser = tokenService.getLoginUser(request);
            if (loginUser == null) {
                return Result.fail("用户未登录");
            }
            
            AjaxResult result = userService.followUser(loginUser.getUserId(), targetUserId);

                return Result.ok("关注成功");


        } catch (Exception e) {
            log.error("关注用户失败", e);
            return Result.fail("关注失败");
        }
    }

    /**
     * 取消关注用户
     * @param targetUserId 目标用户ID
     * @return 操作结果
     */
    @DeleteMapping("/user/follow")
    public Result unfollowUser(@RequestParam("targetUserId") Long targetUserId, HttpServletRequest request) {
        try {
            LoginUser loginUser = tokenService.getLoginUser(request);
            if (loginUser == null) {
                return Result.fail("用户未登录");
            }
            
            AjaxResult result = userService.unfollowUser(loginUser.getUserId(), targetUserId);
                return Result.ok("取消关注成功");

        } catch (Exception e) {
            log.error("取消关注用户失败", e);
            return Result.fail("取消关注失败");
        }
    }

    /**
     * 检查是否已关注
     * @param targetUserId 目标用户ID
     * @return 是否已关注
     */
    @GetMapping("/user/isFollowing")
    public Result isFollowing(@RequestParam("targetUserId") Long targetUserId, HttpServletRequest request) {
        try {
            LoginUser loginUser = tokenService.getLoginUser(request);
            if (loginUser == null) {
                return Result.fail("用户未登录");
            }
            
            AjaxResult result = userService.isFollowing(loginUser.getUserId(), targetUserId);
            return Result.ok(result.get("isFollowing"));
        } catch (Exception e) {
            log.error("检查关注状态失败", e);
            return Result.fail("检查失败");
        }
    }

    /**
     * 发送邮箱验证码
     * @param emailCodeDTO 邮箱验证码请求参数
     * @return 操作结果
     */
    @PostMapping("/user/sendEmailCode")
    public AjaxResult sendEmailCode(@RequestBody EmailCodeDTO emailCodeDTO) {
        try {
            return emailService.sendEmailCode(emailCodeDTO.getEmail(), emailCodeDTO.getType());
        } catch (Exception e) {
            log.error("发送邮箱验证码失败", e);
            return AjaxResult.error("发送验证码失败");
        }
    }

    /**
     * 用户注册
     * @param registerDTO 注册信息
     * @return 操作结果
     */
    @PostMapping("/user/register")
    public AjaxResult register(@RequestBody RegisterDTO registerDTO) {
        try {
            // 验证必填字段
            if (registerDTO.getUsername() == null || registerDTO.getUsername().trim().isEmpty()) {
                return AjaxResult.error("用户名不能为空");
            }
            if (registerDTO.getPassword() == null || registerDTO.getPassword().trim().isEmpty()) {
                return AjaxResult.error("密码不能为空");
            }
            if (registerDTO.getEmail() == null || registerDTO.getEmail().trim().isEmpty()) {
                return AjaxResult.error("邮箱不能为空");
            }
            if (registerDTO.getEmailCode() == null || registerDTO.getEmailCode().trim().isEmpty()) {
                return AjaxResult.error("验证码不能为空");
            }

            // 验证两次密码是否一致
            if (!registerDTO.getPassword().equals(registerDTO.getConfirmPassword())) {
                return AjaxResult.error("两次输入的密码不一致");
            }

            // 验证邮箱验证码
            AjaxResult verifyResult = emailService.verifyEmailCode(
                registerDTO.getEmail(), 
                registerDTO.getEmailCode(), 
                "register"
            );
            if (verifyResult.get("code") != null && !(Boolean.TRUE.equals(verifyResult.get("code").equals(200)))) {
                return verifyResult;
            }

            // 创建用户对象
            SpffUsers user = new SpffUsers();
            user.setUsername(registerDTO.getUsername());
            user.setPassword(registerDTO.getPassword());
            user.setEmail(registerDTO.getEmail());
            user.setNickname(registerDTO.getNickname());

            // 注册用户
            AjaxResult result = userService.register(user);

            // 注册成功后删除验证码
            if (result.get("code") != null && result.get("code").equals(200)) {
                emailService.deleteEmailCode(registerDTO.getEmail(), "register");
            }

            return result;
        } catch (Exception e) {
            log.error("用户注册失败", e);
            return AjaxResult.error("注册失败，请稍后重试");
        }
    }

    /**
     * 重置密码
     * @param resetPasswordDTO 重置密码信息
     * @return 操作结果
     */
    @PostMapping("/user/resetPassword")
    public AjaxResult resetPassword(@RequestBody ResetPasswordDTO resetPasswordDTO) {
        try {
            // 验证必填字段
            if (resetPasswordDTO.getEmail() == null || resetPasswordDTO.getEmail().trim().isEmpty()) {
                return AjaxResult.error("邮箱不能为空");
            }
            if (resetPasswordDTO.getNewPassword() == null || resetPasswordDTO.getNewPassword().trim().isEmpty()) {
                return AjaxResult.error("新密码不能为空");
            }
            if (resetPasswordDTO.getEmailCode() == null || resetPasswordDTO.getEmailCode().trim().isEmpty()) {
                return AjaxResult.error("验证码不能为空");
            }

            // 验证两次密码是否一致
            if (!resetPasswordDTO.getNewPassword().equals(resetPasswordDTO.getConfirmPassword())) {
                return AjaxResult.error("两次输入的密码不一致");
            }

            // 验证邮箱验证码
            AjaxResult verifyResult = emailService.verifyEmailCode(
                resetPasswordDTO.getEmail(), 
                resetPasswordDTO.getEmailCode(), 
                "reset"
            );
            if (verifyResult.get("code") != null && !(Boolean.TRUE.equals(verifyResult.get("code").equals(200)))) {
                return verifyResult;
            }

            // 重置密码
            AjaxResult result = userService.resetPassword(
                resetPasswordDTO.getEmail(), 
                resetPasswordDTO.getNewPassword()
            );

            // 重置成功后删除验证码
            if (result.get("code") != null && result.get("code").equals(200)) {
                emailService.deleteEmailCode(resetPasswordDTO.getEmail(), "reset");
            }

            return result;
        } catch (Exception e) {
            log.error("重置密码失败", e);
            return AjaxResult.error("重置密码失败，请稍后重试");
        }
    }

    /**
     * 检查用户名是否已存在
     * @param username 用户名
     * @return 操作结果
     */
    @GetMapping("/user/checkUsername")
    public AjaxResult checkUsername(@RequestParam("username") String username) {
        try {
            return userService.checkUserExists(username);
        } catch (Exception e) {
            log.error("检查用户名失败", e);
            return AjaxResult.error("检查失败");
        }
    }

    /**
     * 上传用户头像
     * @param avatarUrl 头像URL（由前端先上传文件获得）
     * @param request HTTP请求
     * @return 操作结果
     */
    @PostMapping("/user/uploadAvatar")
    public AjaxResult uploadAvatar(@RequestParam("avatarUrl") String avatarUrl, HttpServletRequest request) {
        try {
            LoginUser loginUser = tokenService.getLoginUser(request);
            if (loginUser == null) {
                return AjaxResult.error("用户未登录");
            }
            
            return userService.uploadAvatar(loginUser.getUserId(), avatarUrl);
        } catch (Exception e) {
            log.error("上传头像失败", e);
            return AjaxResult.error("上传头像失败");
        }
    }

}
